package com.browsesoft.htmlcomponent;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Element;

import com.aote.util.ComponentHelper;
import com.browsesoft.ExtendElement;
import com.browsesoft.baseadapter.AdvancedSimpleEntity;

public class selectGropComponent extends ReplacableParameterComponent {
	// 被选中的元素的名字
	private String value = new String();

	// 被选中的元素
	private Element ele;

	// 选择组名字
	private String riodName = new String();

	public selectGropComponent(HTMLBasicComponent parent) throws Exception {
		super(parent);
		// TODO Auto-generated constructor stub
	}

	/**
	 * 
	 */
	public void init(HttpServletRequest request, Element e) throws Exception {
		super.init(request, e);
		Iterator iter = ExtendElement.findElements(e, "radiogrop", "radiogrop")
				.iterator();
		while (iter.hasNext()) {
			Element elem = (Element) iter.next();
			if (elem.hasAttribute("checked")) {
				this.ele = elem;
			}
			this.riodName = elem.getAttribute("name");
		}
	}

	/**
	 * 
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		super.service(request, response);
		// 取出选中的 按钮的名字
		this.value = request.getParameter(this.riodName);
		if (this.value == null || this.value.equals("")) {
			if (this.ele != null) {
				this.value = this.ele.getAttribute("value");
			}
		}
		this.dispose(request, response);
	}

	/**
	 * @throws Exception
	 * 
	 */
	private void dispose(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 如果没有选择，处理默认值
		if (this.value == null || this.value.equals("")) {
			return;
		}
		// 如果没有处理的属性，不处理
		String name = this.getElement().getAttribute("resultname");
		// 将选择结果保存到Form组件中
		AdvancedSimpleEntity entity = (AdvancedSimpleEntity) ComponentHelper
				.getFormEntity(this);
		entity.getAttributes().put(name, this.value);
		String action = (String) request.getParameter("action");
		if (action != null && action.equals("search")) {
			entity.getAttributes().remove("checked");
		} else {
			entity.getAttributes().put("checked", this.value);
		}
		 entity.service(request, response);
		entity.getComponent().updateElement();
	}

	/**
	 * 
	 */
	protected void updateElement() throws Exception {
		super.updateElement();
		// 如果没有选，保持原状态
		if (this.value == null || this.value.equals("")) {
			if (this.ele != null) {
				this.ele.setAttribute("checked", "checked");
			}
			return;
		}
		// 设置选中状态
		Iterator iter = ExtendElement.findElements(this.element, "radiogrop",
				"radiogrop").iterator();
		while (iter.hasNext()) {
			Element elem = (Element) iter.next();
			if (elem.getAttribute("value").equals(this.value)) {
				this.ele = elem;
				elem.setAttribute("checked", "checked");
			} else {
				elem.removeAttribute("checked");
			}
		}
	}

}
